package com.codeplex.jtfscli.util;

import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class ArgParser {
	/**
	 * Parses command line arguments passed to the program. This client accepts
	 * arguments starting with both "/" and "-", however, simplify development
	 * later on, all leading "/" characters are converted to "-". We leave the
	 * "-" character to differentiate flags from regular arguments.
	 * 
	 * For flags (e.g. /new) the mapping will be "-new" -> "" (empty string).
	 * For values (e.g. -server:localhost) the mapping will be "-server" ->
	 * "localhost" For named parameters (e.g. MYCOMPUTERNAME) the mapping will
	 * be "MYCOMPUTERNAME" -> "MYCOMPUTERNAME".
	 * 
	 * @param args
	 *            The collection of arguments passed to the program on the
	 *            command line.
	 * @return
	 */
	public static Map<String, String> parse(final Collection<String> args) {
		final Map<String, String> ret = new TreeMap<String, String>();
		for (final String arg : args) {
			if (arg.startsWith("/") || arg.startsWith("-")) {
				final int valueSeparatorIndex = arg.indexOf(':');
				if (valueSeparatorIndex == -1)
					ret.put("-" + arg.substring(1), "");
				else
					ret.put("-" + arg.substring(1, valueSeparatorIndex),
							arg.substring(valueSeparatorIndex + 1));
			} else
				ret.put(arg, arg);
		}
		return ret;
	}

	/**
	 * Finds the first occurrence in parsedArgs of a regular parameter (a
	 * parameter not starting with "/" or "-").
	 * 
	 * @param args
	 * @return
	 */
	public static List<String> findRegularArgs(final List<String> args) {
		final List<String> ret = new LinkedList<String>();
		for (final String s : args) {
			if (!s.startsWith("-") && !s.startsWith("/"))
				ret.add(s);
		}
		return ret;
	}
}
